const router = require('koa-router')();
router.prefix('/film');
let Film = require('../models/film.js');
let Order = require('../models/order.js');

/**
 * 获取电影列表
 */
router.get('/getFilm', async (ctx, next) => {
  try {
    let { id = '', page = 1, size = 10 } = ctx.query;
    page = +page;
    size = +size;
    let obj = {};
    if (id) {
      obj.doubanId = id;
    }
    let Flist = await Film.find(obj).skip((page - 1) * size).limit(size);
    let count = await Film.find(obj).countDocuments();
    ctx.success({Flist, count});
  } catch (err) {
    throw err;
  }
});
/**
 *更新电影信息
 */
router.post('/updateFilm', async (ctx, next) => {
  try {
    let { _id = '', title = '', country = '', price = 0, year = '', rate = '', directors = '', actors = '',
      genre = '', coverurl = '', poster = '', videoUrl = '', aka = '', summary = ''
    } = ctx.request.body;
    if (!_id) {
      throw new Error('缺少参数');
    }
    let obj = {};
    title && (obj.original_title = title);
    country && (obj.countries = country);
    price && (obj.price = price);
    year && (obj.year = year);
    rate && (obj.rate = rate);
    directors && (obj.directors = directors);
    actors && (obj.actors = actors);
    genre && (obj.genres = genre);
    coverurl && (obj.coverurl = coverurl);
    poster && (obj.poster = poster);
    videoUrl && (obj.videoUrl = videoUrl);
    aka && (obj.aka = aka);
    summary && (obj.summary = summary);
    await Film.updateOne({_id}, {$set: obj});
    ctx.success({msg: `update success`});
  } catch (err) {
    throw err;
  }
});

/**
 * 获取不同种类的电影
 */
router.get('/getFilmType', async (ctx, next) => {
  try {
    let { type = '' } = ctx.query;
    if (!type) {
      throw new Error('缺少参数');
    } else {
      let films = await Film.find({genres: type, status: true}).limit(7);
      let myFilms = [];
      let orderFilms = [];
      if (ctx.userId) {
        let myOrder = await Order.find({userId: ctx.userId, status: 1});
        for (let i = 0; i < myOrder.length; i++) {
          orderFilms = orderFilms.concat(myOrder[i].films);
        }
        myFilms = orderFilms.map(item => item.doubanId);
      }
      films.forEach(item => {
        if (myFilms.includes(item.doubanId)) {
          item._doc.isMyFilm = true;
        } else {
          item._doc.isMyFilm = false;
        }
      });

      ctx.success(films);
    }
  } catch (err) {
    throw err;
  }
});

/**
 * 电影上下架
 * @type {[type]}
 */
router.post('/upOrDown', async (ctx, next) => {
  try {
    let { status, id } = ctx.request.body;
    await Film.updateOne({doubanId: id}, {$set: {status}});
    ctx.success(`修改成功`);
  } catch (err) {
    throw err;
  }
});
module.exports = router
;
